<template>
  <div class="components-layout-demo" >
    <a-layout style="height:100%">
      <a-layout style="background: #fff;height:100%">
        <a-layout-sider  class="layout-sider-left">
          <div style="height:100%;">
            <sidebar-check-user
              :deptTree="deptTree"
              :deptChecked.sync="deptCheckedLeft"
              :userChecked.sync="userCheckedLeft"
              :userSerialChecked.sync="userSerialCheckedLeft"
              @on-check="serchByChecked"
              @on-select="serchByselected"
              :heightTree="heightTreeLeft"
              :heightTable="heightTableLeft"
              :setHeight="'13px'"
            />
          </div>
        </a-layout-sider>
        <a-layout-content class="layoutContent">
          <div class="components-table-demo-size" style="height:100%">
            <!-- tools盒子 每个页面必须存在的div盒子，除了表格以外的功能都放在这个里面 -->
            <div id="tools">
              <div class="height8"></div>

              <a-form layout="inline" style="text-align: left;padding: 0 10px;" :selfUpdate="true">
                <a-form-item label="关键字" class="marginBtm">
                  <a-input v-model="searchNameRight"
                           allowClear placeholder="请输入工号/姓名/卡号查询" class="marginBtm"
                           @pressEnter="handleQuery"/>
                </a-form-item>

                <a-form-item class="marginBtm">
                  <a-button type="primary" @click="handleQuery">
                    查询
                  </a-button>
                </a-form-item>
              </a-form>

              <a-divider style="margin: 5px 0"/>

              <!-- 功能按钮 -->
              <div class="divPadiAlign">
                <a-button type="primary" class="button-marin" @click="modalAccess=true">
                  授权
                </a-button>
                <a-button type="primary" class="button-marin" @click="handleRemove">
                  撤销
                </a-button>
                <a-button type="primary" class="button-marin" @click="handleExport">
                  导出
                </a-button>
              </div>

            </div>
            <!-- 右侧数据表格 -->
            <div  id="tableBox" class="tableOthStyle">
              <a-table
                bordered
                size="small"
                :columns="columnsRight"
                :scroll="{y: yHeight}"
                :dataSource="listRight"
                :loading="tableLoading"
                :rowKey="(record) => record.xh"
                :rowSelection="{selectedRowKeys: checkedXhRight, onChange: onChangeRight}"
                :pagination="paginationRight"
              />
            </div>
          </div>
        </a-layout-content>
      </a-layout>
      <!-- 授权模态框 -->
      <a-modal
        :destroyOnClose="true"
        :maskClosable="false"
        :keyboard="false"
        @ok="handleAccessOk"
        @cancel="handleAccessCancel"
        v-model="modalAccess"
        :dialog-style="{ top: '20px' }"
        class="form"
        title="门禁授权"
        width="900px"
        height="600px"
        :bodyStyle="{padding: '10px'}"
      >
        <a-row>
          <a-col>
            <!-- 选择员工 -->
            <a-row type="flex" align="top" justify="space-between">
              <a-col :span="8">
                <!-- 部门-用户 -->
                <div class="borderBox">
                    <sidebar-check-user
                    :deptTree="deptTree"
                    :deptChecked.sync="deptCheckedModal"
                    :userChecked.sync="userCheckedModal"
                    :heightTree="heightTreeModal"
                    :heightTable="heightTableModal"

                    />
                </div>
              </a-col>
              <a-col :span="2">
                <!-- 操作-按钮 -->
                    <div style="margin:100px 0px 0px 0px"></div>
                    <a-button @click="toUserRight" block>&gt;&gt;</a-button>
                    <div style="margin:30px 0px"></div>
                    <a-button @click="toUserLeft" block>&lt;&lt;</a-button>

              </a-col>
              <a-col :span="12">
                <!-- 准备授权人员 -->
                <div class="borderBox">
                  <div style="padding: 10px 10px 0 10px">
                    <a-table
                      size="small"
                      class="a-table"
                      bordered
                      :pagination="{simple:true,pageSize:20}"
                      :scroll="{y: 198}"
                      :columns="userAccessColumnsModal"
                      :dataSource="userAccessListModal"
                      :rowKey="(record) => record.userSerial"
                      :rowSelection="{selectedRowKeys: userSerialAccessCheckedModal, onChange: onChangeAccessUserModal}"
                    />
                  </div>
                </div>
              </a-col>
            </a-row>

            <a-divider style="margin: 10px 0"/>

            <!-- 选择场所 -->
            <a-row type="flex" align="top" justify="space-between">
              <a-col :span="8">
                  <div class="borderBox">
                <!-- 场所-门 -->
                <sidebar-check-door
                  :placeTree="placeTree"
                  :placeChecked.sync="placeCheckedModal"
                  :doorChecked.sync="doorCheckedModal"
                  :heightTree="heightTreeModal"
                  :heightTable="heightTableModal"
                />
                </div>
              </a-col>
              <a-col :span="2">
                <!-- 操作-按钮 -->

                    <div style="margin:100px 0px 0px 0px"></div>
                    <a-button @click="toDoorRight" block>&gt;&gt;</a-button>
                    <div style="margin:30px 0px"></div>
                    <a-button @click="toDoorLeft" block>&lt;&lt;</a-button>

              </a-col>
              <a-col :span="12">
                  <div class="borderBox">
                    <div style="padding: 10px 10px 0 10px">
                      <a-table
                        size="small"
                        class="a-table"
                        bordered
                        :pagination="{simple:true,pageSize:20}"
                        :columns="doorAccessColumnsModal"
                        :scroll="{y: 198}"
                        :dataSource="doorAccessListModal"
                        :rowKey="(record) => record.doorBh"
                        :rowSelection="{selectedRowKeys: doorBhAccessCheckedModal, onChange: onChangeAccessDoorModal}"
                      />
                    </div>
                </div>
              </a-col>
            </a-row>

            <a-divider style="margin: 10px 0"/>
            <!-- 规则 -->
              <a-form layout="inline" style="padding: 0 10px;">

                    <a-form-item label="进门规则">
                      <a-select v-model="inDoorRuleNo" style="width: 120px">
                        <a-select-option
                          v-for="rule in doorRuleList"
                          :key="rule.ruleNo"
                          :value="rule.ruleNo"
                        >{{rule.ruleName}}</a-select-option>
                      </a-select>
                    </a-form-item>

                    <a-form-item label="出门规则">
                      <a-select v-model="outDoorRuleNo" style="width: 120px">
                        <a-select-option
                          v-for="rule in doorRuleList"
                          :key="rule.ruleNo"
                          :value="rule.ruleNo"
                        >{{rule.ruleName}}</a-select-option>
                      </a-select>
                    </a-form-item>

              </a-form>

          </a-col>
        </a-row>
      </a-modal>
    </a-layout>
  </div>
</template>

<script>
import sidebarCheckDoor from "@/components/accessControlSystem/sidebarCheckDoor.vue";
import sidebarCheckUser from "@/components/accessControlSystem/sidebarCheckUser.vue";
import { tableBoxHeight } from "@/api/communal";
import dept from "@/api/accessControlSystem/dept";
import place from "@/api/accessControlSystem/place";
import door from "@/api/accessControlSystem/door";
import rule from "@/api/accessControlSystem/rule";

import api from "@/config/config";

export default {
  components: {
    sidebarCheckDoor,
    sidebarCheckUser
  },
  mounted() {
    let _this = this;
    //加载树形结构数据
    dept.getTreeList().then(res => {
      // console.log(res)
      _this.deptTree = res.data.result;
    });
    place.getTreeList().then(res => {
      // console.log(res)
      _this.placeTree = res.data.result;
    });
    rule.getDoorRule().then(res => {
      // console.log(res)
      _this.doorRuleList = res.data.result;
      // console.log(_this.doorRuleList)
    });
    this.yHeight = tableBoxHeight();
    // 控制表格底部边框保持在底部，而不是在半空中
    let minHeight = document.getElementsByClassName("ant-table");
    minHeight[0].style.minHeight = tableBoxHeight() + 40 + "px";
    // 计算本页面左侧高度传值给组
        let height = window.innerHeight;
        // 减的数值具体可参考communal.js
      this.heightTableLeft = String(height - 225 - 60);
      this.heightTreeLeft = "height:" + (height - 187) + "px";
  },
  data() {
    let _this = this;
    return {
      inDoorRuleNo: 1,
      outDoorRuleNo: 1,
      doorRuleList: [],

      //树形结构
      deptTree: [],
      placeTree: [],

      /* 左侧 */
      heightTreeLeft:"",
      heightTableLeft:"500",
      deptCheckedLeft: [],
      deptselectedLeft:[],
      userCheckedLeft: [],
      userSerialCheckedLeft: [],

      /* 右侧  */
      yHeight: 500,
      heightTreeModal: "maxHeight:196px",
      heightTableModal: "114",
      pageNoRight: 1,
      pageSizeRight: 20,
      searchNameRight: "",
      tableLoading: false,
      listRight: [], //[{"inRule":"规则1","smtName":"郭永超","bh":"0010026","doorName":"步达东门","smtDeptname":"信息系统部","smtCardno":"723896960","id":3938,"smtSalaryno":"8811157","devOrder":1,"depName":"默认场所","outRule":"规则1","ROW_ID":1},{"inRule":"规则1","smtName":"郭永超","bh":"0010026","doorName":"步达西门","smtDeptname":"信息系统部","smtCardno":"723896960","id":3941,"smtSalaryno":"8811157","devOrder":4,"depName":"默认场所","outRule":"规则1","ROW_ID":2},{"inRule":"规则1","smtName":"郭永超","bh":"0010026","doorName":"步达南门","smtDeptname":"信息系统部","smtCardno":"723896960","id":3940,"smtSalaryno":"8811157","devOrder":2,"depName":"默认场所","outRule":"规则1","ROW_ID":3},{"inRule":"规则1","smtName":"郭永超","bh":"0010026","doorName":"步达北门","smtDeptname":"信息系统部","smtCardno":"723896960","id":3939,"smtSalaryno":"8811157","devOrder":3,"depName":"默认场所","outRule":"规则1","ROW_ID":4},{"inRule":"规则1","smtName":"郭永超","bh":"0010026","doorName":"步达北门","smtDeptname":"信息系统部","smtCardno":"723896960","id":3939,"smtSalaryno":"8811157","devOrder":3,"depName":"默认场所","outRule":"规则1","ROW_ID":4},{"inRule":"规则1","smtName":"郭永超","bh":"0010026","doorName":"步达北门","smtDeptname":"信息系统部","smtCardno":"723896960","id":3939,"smtSalaryno":"8811157","devOrder":3,"depName":"默认场所","outRule":"规则1","ROW_ID":4},{"inRule":"规则1","smtName":"郭永超","bh":"0010026","doorName":"步达北门","smtDeptname":"信息系统部","smtCardno":"723896960","id":3939,"smtSalaryno":"8811157","devOrder":3,"depName":"默认场所","outRule":"规则1","ROW_ID":4},{"inRule":"规则1","smtName":"郭永超","bh":"0010026","doorName":"步达北门","smtDeptname":"信息系统部","smtCardno":"723896960","id":3939,"smtSalaryno":"8811157","devOrder":3,"depName":"默认场所","outRule":"规则1","ROW_ID":4},{"inRule":"规则1","smtName":"郭永超","bh":"0010026","doorName":"步达北门","smtDeptname":"信息系统部","smtCardno":"723896960","id":3939,"smtSalaryno":"8811157","devOrder":3,"depName":"默认场所","outRule":"规则1","ROW_ID":4},{"inRule":"规则1","smtName":"郭永超","bh":"0010026","doorName":"步达北门","smtDeptname":"信息系统部","smtCardno":"723896960","id":3939,"smtSalaryno":"8811157","devOrder":3,"depName":"默认场所","outRule":"规则1","ROW_ID":4},{"inRule":"规则1","smtName":"郭永超","bh":"0010026","doorName":"步达北门","smtDeptname":"信息系统部","smtCardno":"723896960","id":3939,"smtSalaryno":"8811157","devOrder":3,"depName":"默认场所","outRule":"规则1","ROW_ID":4}],
      checkedXhRight: [], // Check here to configure the default column
      columnsRight: [
        {
          title: "场所名称",
          dataIndex: "placeName",
          align: "center",
          width: '12%',
          className: 'changeBack'
        },
        {
          title: "门名称",
          dataIndex: "doorName",
          align: "center",
          width: '18%',
          className: 'changeBack'
        },
        {
          title: "姓名",
          dataIndex: "userName",
          align: "center",
          width: '12%',
          className: 'changeBack'
        },
        {
          title: "工号",
          dataIndex: "userNo",
          align: "center",
          width: '12%',
          className: 'changeBack'
        },
        {
          title: "卡号",
          dataIndex: "userCard",
          align: "center",
          width: '12%',
          className: 'changeBack'
        },
        {
          title: "部门",
          dataIndex: "deptName",
          align: "center",
          width: '12%',
          className: 'changeBack'
        },
        {
          title: "规则名称",
          dataIndex: "ruleName",
          align: "center",
          width: '12%',
          className: 'changeBack'
        },
        {
          title: "方向",
          dataIndex: "fx",
          align: "center",
          width: '10%',
          className: 'changeBack'
        }
      ],
      paginationRight: {
        size: "small",
        current: 1,
        pageSize: 20, // 默认每页显示数量
        total: 0, //总条数
        showSizeChanger: true, // 显示可改变每页数量
        pageSizeOptions: ["20", "30", "50"], // 每页数量选项
        showTotal: total => `共 ${total} 条数据`, // 显示总数
        onShowSizeChange: (current, pageSize) => _this.changePageRight(1, pageSize), // 改变每页数量时更新显示
        onChange: (current, pageSize) => _this.changePageRight(current, pageSize) //点击页码事件
      },

      // 授权模态框
      // 选择部门-人员
      modalAccess: false,
      deptCheckedModal: [],   //选择的部门
      userCheckedModal: [],   //选择的人员
      userAccessListModal: [],
      userSerialAccessCheckedModal: [],
      userAccessColumnsModal: [
        {
          title: "姓名",
          dataIndex: "userName",
          align: "center",
          width:"45%",
          className: 'changeBack'
        },
        {
          title: "工号",
          dataIndex: "userNo",
          align: "center",
          width:"45%",
          className: 'changeBack'
        }
      ],
      // 选择场所-门
      placeCheckedModal: [],
      doorCheckedModal: [],
      doorAccessListModal: [],
      doorBhAccessCheckedModal: [],
      doorAccessColumnsModal: [
        {
          title: "场所",
          dataIndex: "placeName",
          align: "center",
          width:"45%",
          className: 'changeBack'
        },
        {
          title: "门名称",
          dataIndex: "doorName",
          align: "center",
          width:"45%",
          className: 'changeBack'
        }
      ],
      loading: true
    };
  },
  methods: {
    /**
     * 右侧方法
     */
    // 分页刷新
    changePageRight(current, pageSize) {
      this.paginationRight.current = current;
      this.paginationRight.pageSize = pageSize;
      this.getDoorAccessList();
    },
    serchByChecked(value){
      this.paginationRight.current = 1;
      this.deptCheckedLeft = value;
      this.deptselectedLeft = [];
      this.getDoorAccessList()

    },
    serchByselected(value){
      this.paginationRight.current = 1;
      this.deptselectedLeft = value;
      this.deptCheckedLeft = [];
      this.getDoorAccessList()

    },
    // 点击搜索
    handleQuery() {
      this.paginationRight.current = 1;
      this.getDoorAccessList()
    },
    //查询有权限员工
    getDoorAccessList() {
      let _this = this;
      let placeIdArr = [];
      placeIdArr = placeIdArr.concat(this.deptCheckedLeft);
      placeIdArr = placeIdArr.concat(this.deptselectedLeft);
      this.tableLoading = true;
      door
        .getDoorAccessList({
          current: this.paginationRight.current,
          pageSize: this.paginationRight.pageSize,
          searchName: this.searchNameRight,
          userSerial: this.userSerialCheckedLeft.join(","),
          deptSerial: placeIdArr.join(",")
        })
        .then(res => {
          // console.log(res)
          if (res.data.success) {
            _this.tableLoading = false;
            _this.checkedXhRight = [];
            _this.listRight = res.data.result.records;
            _this.paginationRight.total = res.data.result.total;
          } else {
            _this.tableLoading = false;
            _this.$message.error(res.data.message);
          }
        });
    },
    // 点击授权确定按钮
    handleAccessOk() {
      let userSerial = [];
      let doorBh = [];
      this.$message.destroy();
      for (let user of this.userAccessListModal) {
        userSerial.push(user.userSerial);
      }
      for (let door of this.doorAccessListModal) {
        doorBh.push(door.doorBh);
      }
      if (userSerial.length == 0) {
        this.$message.warning("请选择需要授权人员!");
      } else if (doorBh.length == 0) {
        this.$message.warning("请选择需要授权门!");
      } else {
        door
          .doorAccess({
            inDoorRuleNo: this.inDoorRuleNo,
            outDoorRuleNo: this.outDoorRuleNo,
            userSerial: userSerial.join(","),
            doorBh: doorBh.join(",")
          })
          .then(res => {
            // console.log(res)
            if (res.data.code == 200) {
              if (res.data.result == 0) {
                this.$message.error("授权指定下发失败!");
              } else {
                this.changePageRight(1,this.paginationRight.pageSize);
                this.handleAccessCancel();
                this.$message.success("授权指定下发成功!");
              }
            } else {
              this.$message.error("请求出现异常!");
            }
          });
      }
    },
    // 点击取消模态框
    handleAccessCancel() {
      this.modalAccess = false;
      this.userAccessListModal = [];
      this.userSerialAccessCheckedModal = [];
      this.doorAccessListModal = [];
      this.doorBhAccessCheckedModal = [];
    },
    // 点击撤销按钮
    handleRemove() {
      let _this = this;
      this.$message.destroy();
      let xh = this.checkedXhRight.join(",");
      if (xh == "" || xh == null) {
        this.$message.warning("请选择需要撤销权限人员!");
      } else {
        this.$confirm({
          width: 500,
          okText: "确定",
          cancelText: "取消",
          title: "操作提示信息",
          content: h => '确定要撤销选中的权限吗?',
          onOk() {
            door
              .doorAccessRemove({
                xh: _this.checkedXhRight.join(",")
              })
              .then(res => {
                if (res.data.code == 200) {
                  if (res.data.result > 0) {
                    _this.changePageRight(1,_this.paginationRight.pageSize);
                    _this.$message.success("撤销权限成功!");
                  } else {
                    _this.$message.error("撤销权限失败!");
                  }
                } else {
                  _this.$message.error("请求出现异常!");
                }
              });
          },
          onCancel() {
          },
          class: "test"
        });
      }
    },
    // 点击导出
    handleExport() {
      let parameter =
        "searchName=" +
        this.searchNameRight +
        "&userSerial=" +
        this.userSerialCheckedLeft.join(",") +
        "&deptSerial=" +
        this.deptCheckedLeft.join(",");
      window.open(
        api.apiUrl + "api/door/doorAccessExport?" + parameter,
        "_self"
      );
    },
    // 选中授权表格
    onChangeRight(selectKeys) {
      this.checkedXhRight = selectKeys;
    },

    // 添加授权人
    toUserRight() {
      for (let user of this.userCheckedModal) {
        let flag = true;
        for (let u of this.userAccessListModal) {
          if (user.userSerial == u.userSerial) {
            flag = false;
            break;
          }
        }
        if (flag) {
          this.userAccessListModal.push(user);
        }
      }
      // console.log(this.userAccessListModal)
    },
    // 选中准备授权人
    onChangeAccessUserModal(selectKeys) {
      this.userSerialAccessCheckedModal = selectKeys;
    },
    // 移除授权人
    toUserLeft() {
      this.userAccessListModal = this.userAccessListModal.filter(
        user =>
          !this.userSerialAccessCheckedModal.find(
            userSerial => user.userSerial == userSerial
          )
      );
      this.userSerialAccessCheckedModal = [];
    },
    // 选中准备授权门
    onChangeAccessDoorModal(selectKeys) {
      this.doorBhAccessCheckedModal = selectKeys;
    },
    // 添加授权门
    toDoorRight() {
      for (let door of this.doorCheckedModal) {
        let flag = true;
        for (let d of this.doorAccessListModal) {
          if (door.doorBh == d.doorBh) {
            flag = false;
            break;
          }
        }
        if (flag) {
          this.doorAccessListModal.push(door);
        }
      }
    },
    // 移除授权门
    toDoorLeft() {
      this.doorAccessListModal = this.doorAccessListModal.filter(
        door =>
          !this.doorBhAccessCheckedModal.find(doorBh => door.doorBh == doorBh)
      );
      this.doorBhAccessCheckedModal = [];
    }
  }
};
</script>

<style>
.rule {
  border: 1px solid #eee;
  margin: 10px 0px 0 0;
  padding: 7px 0px;
}

</style>
